package com.atom.app.mvvm.ui.activities

import android.content.Intent
import android.os.Bundle
import android.text.Editable
import android.view.View
import androidx.databinding.ObservableBoolean
import androidx.databinding.ObservableField
import androidx.lifecycle.ViewModelProvider
import com.atom.app.mvvm.AppModel
import com.atom.app.mvvm.BR
import com.atom.app.mvvm.R
import com.atom.app.mvvm.VMFactory
import com.atom.app.mvvm.abase.BaseKingViewModel
import com.atom.app.mvvm.Contacts
import com.atom.app.mvvm.databinding.ActivityLoginBinding
import com.atom.app.mvvm.net.BaseResponse
import com.atom.app.mvvm.net.bean.LoginResult
import com.atom.app.mvvm.net.dto.LoginUser
import com.atom.app.mvvm.utils.JacksonUtils
import com.atom.module.logger.Logger
import com.atom.module.mvvm.adapter.BooleanEvent
import com.atom.module.mvvm.adapter.ClickEvent
import com.atom.module.mvvm.adapter.TextWatcherEvent
import com.atom.module.mvvm.base.view.activity.AbstractBaseMVVMActivity
import com.atom.module.mvvm.util.Auto
import com.tencent.mmkv.MMKV
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers
import io.reactivex.rxjava3.internal.observers.BlockingBaseObserver
import io.reactivex.rxjava3.schedulers.Schedulers

class LoginActivity : AbstractBaseMVVMActivity<ActivityLoginBinding, LoginViewModel>() {


    override fun initArgs(intent: Intent, savedInstanceState: Bundle?): Boolean {
        Auto.registerTask(this::class) { app ->
            viewModel.account.set("admin")
            viewModel.password.set("admin")
//            viewModel.loginEvent.invoke(binding.root)
            true
        }
        return super.initArgs(intent, savedInstanceState)
    }

    override fun initContentView(savedInstanceState: Bundle?): Int {
        return R.layout.activity_login
    }

    override fun initViewModel(): LoginViewModel {
        return ViewModelProvider(this, VMFactory).get(LoginViewModel::class.java)
    }

    override fun initVariableId(): Int {
        return BR.loginViewModel
    }

    override fun onResume() {
        super.onResume()
        Logger.e(Auto.startTask(this))
    }
}

class LoginViewModel : BaseKingViewModel<AppModel>(AppModel) {

    val password = ObservableField("")
    val loginEvent = object : ClickEvent() {
        override fun invoke(t: View) {
            MMKV.defaultMMKV().encode(Contacts.tag_is_first, true)
            if (account.get().isNullOrEmpty()) {
                toast("请输入账号")
                return
            }
            if (password.get().isNullOrEmpty()) {
                toast("请输入密码")
                return
            }
            if (!agreementAndPrivacy.get()) {
            }
            addSubscribe(
                model.netApi.loginJson(LoginUser(account.get(), password.get()))
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribeWith(object : BlockingBaseObserver<BaseResponse<LoginResult>>() {
                        override fun onNext(t: BaseResponse<LoginResult>) {
                            Logger.i(JacksonUtils.objectMapper.writeValueAsString(t))
                            if (t.code == 1) {
                                // 解析数据 存入MMKV
                                model.tokenAccessSave(t.data?.token)
                                model.tokenRefreshSave(t.data?.refresh)
                                startActivity(MainActivity::class.java)
                                finish()
                            } else {
                                toast("数据异常:${t.msg}")
                            }
                        }

                        override fun onError(e: Throwable) {
                            Logger.e(e)
                        }
                    })
            )
        }
    }
    val isPasswordVisible = ObservableBoolean(false)

    val passwordShowEvent = object : ClickEvent() {
        override fun invoke(t: View) {
            // 开发对应的功能
            isPasswordVisible.set(!isPasswordVisible.get());
        }
    }

    val account = ObservableField("")
    val accountCleanState = ObservableBoolean(false)
    val accountCleanEvent = object : ClickEvent() {
        override fun invoke(t: View) {
            account.set("")
        }
    }
    val accountWatchEvent = object : TextWatcherEvent() {
        override fun afterTextChanged(s: Editable?) {
            s ?: let {
                accountCleanState.set(false)
                return
            }
            accountCleanState.set(s.isNotEmpty())
        }
    }
    val agreementAndPrivacy = object : BooleanEvent() {
        override fun invoke(t: Boolean) {
            if (t) {
                toast("同意隐私协议")
            } else {
                toast("不同意隐私协议")
            }
        }
    }
    val agreementAndPrivacyShowEvent = object : ClickEvent() {
        override fun invoke(t: View) {
            toast(t.resources.getString(R.string.please_wait))
        }
    }
    val registerAccount = object : ClickEvent() {
        override fun invoke(t: View) {
            toast(t.resources.getString(R.string.please_wait))
        }
    }
    val forgetPassword = object : ClickEvent() {
        override fun invoke(t: View) {
            toast(t.resources.getString(R.string.please_wait))
        }
    }

}
